package com.authorization.config;

import com.alibaba.fastjson.JSONObject;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @author chengyadong
 * @date 2023/11/29 10:30
 * @description 自定义登录成功页面
 */
public class SucessHandlerCustomer implements AuthenticationSuccessHandler {
	//登录成功后调用，可以进行用户信息缓存放入session，记录用户登录日志等 将登录成功的返回给前端
	@Override
	public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
		String userName = authentication.getName();
		//获取sessionId放入到response，以便前端获取该值初始化cookie
		String sessionId = request.getSession().getId();
		response.setHeader("cookie-value", sessionId);
		response.setContentType("application/json;charset=UTF-8");
		response.setHeader("Access-Control-Allow-Credentials", "true");
		Map parms = new HashMap();
		parms.put("code","0");
		parms.put("msg",userName+"登录成功");
		response.getWriter().println(JSONObject.toJSON(parms));
	}
}
